<?php

namespace app\controller;

use app\BaseController;
use app\service\FetchManagerService;
use think\facade\{Db, Log};
use think\Exception;
use think\App;
use app\service\StorageService;

class Fetcher extends BaseController
{
    private $fetchManagerService;

    public function __construct(App $app, FetchManagerService $fetchManagerService, StorageService $storageService)
    {
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
        parent::__construct($app);
        $this->fetchManagerService = $fetchManagerService;
        $this->storageService = $storageService;
    }

    public function index(FetchManagerService $fetchService)
    {
        // $rs= $this->fetchService->getLastDataUrlSet();
        $rs = [1 => "/jrNJyBfHxQ.php/coin/usdt/index?sort=usdt.id&order=desc&offset=0&limit=2"];
        return json($rs);

        // $fetchService->createTask();
        return date('Y-m-d H:i:s');

    }

    function test()
    {
        $rs = $this->fetchManagerService->takeTask();
        return json($rs);
    }


    /**
     * /fetcher/takeTask?fetch_url_id=6
     * // 获取 URL 查询字符串
        const queryString = window.location.search;
        // 将查询字符串转换为对象
        const urlParams = new URLSearchParams(queryString);
        // 获取 fetch_url_id 参数值
        const fetchUrlId = urlParams.get('fetch_url_id');
     * @return \think\response\Json
     */
    function takeTask(){
        $fetch_url_id=$this->request->param('fetch_url_id', 0);
        $rs = $this->fetchManagerService->takeTask($fetch_url_id);
        return json($rs);
    }

    function save()
    {
        $rt = [];
        $data = request()->param();

        if ($fetch_log_id = $data['fetch_log_id'] ?? 0 and $remote_total = intval($data['remote_total'] ?? 0)) {
            //$rows = json_decode($data['data'], true);
            // file_put_contents(runtime_path() . 'post4.php', '<?php return ' . var_export($rows, 1) . ";");
            try {
                $rt = $this->storageService->save($fetch_log_id, $remote_total, $data['data']);
            }catch (Exception $exception){
                $msg=$exception->getMessage();
                file_put_contents(runtime_path() . "log_id{$fetch_log_id}total{$remote_total}_err.log", $msg);
                file_put_contents(runtime_path() . "log_id{$fetch_log_id}total{$remote_total}_data.log", $data['data']);
                Log::error($msg);
                return $msg;
            }

        }
        json($rt);
    }

    function getLastDateUrlDict()
    {
        $rs = $this->fetchManagerService->getLastDataUrlSet();
        return json($rs);
    }

    function createTable()
    {

        $rt = [];
        $data = request()->param();
        $total = request()->param('total');
        $table = $data['table'] ?? 'user';
        $rs = Db::query("SHOW TABLES LIKE '$table';");
        if ($total) {
            $rt[] = $this->fetchManagerService->setRemoteTotal($table, $total);
        }


        $rows = json_decode($data['data'] ?? '', true);
        if (!$rs && !empty($rows)) {
            $sql = generateCreateTableSql($table, current($rows));
            $rt[] = $sql;
            DB::query($sql);
        }
        return json($rt);
    }
}
